
// 目标：光线投射用于进行鼠标拾取Raycaster -- 小球贴图

import * as THREE from 'three';
// 导入轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 导入动画库
import gsap from 'gsap';
// 导入快捷界面
import * as dat from 'dat.gui';
// 导入动态纹理加载器
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import { Clock, LightShadow, Material, Mesh, MeshBasicMaterial, Plane, Scene } from 'three';
const svgPath = document.querySelectorAll('.path');

const svgText = anime({
  targets: svgPath,
  loop: true,
  direction: 'alternate',
  strokeDashoffset: [anime.setDashoffset, 0],
  easing: 'easeInOutSine',
  duration: 700,
  delay: (el, i) => { return i * 500 }
});
// 设置场景
const scene = new THREE.Scene();

// 设置相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 20);

// 创建渲染器
const renderer = new THREE.WebGL1Renderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.physicallyCorrectLights = true;

// 导入 坐标系辅助
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 导入轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 设置控制器阻尼
controls.enableDamping = true;
// 设置时钟
let clock = new Clock();

addToScene(scene, camera);
render();

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('./textures/matcaps/xbqichl_4K_Albedo.jpg');
const texturea = textureLoader.load('./textures/matcaps/xbqichl_4K_Albedo.jpg');

const light = new THREE.HemisphereLight(0xffffff, 0x888888);
light.position.set(0, 1, 0);
scene.add(light);

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

window.addEventListener('click', onMouseMove);

const cubeGeo = new THREE.IcosahedronGeometry(0.5, 3);
const material = new THREE.MeshPhongMaterial({
  color: '#fff',
  map: texture
});

const light1 = new THREE.PointLight(0xff0000, 1, 100);
light1.position.set(50, 50, 50);
const geo = new THREE.SphereGeometry(1, 50, 50);
const m1 = new THREE.MeshBasicMaterial({
  color: '#fff'
});
const sp = new THREE.Mesh(geo, m1);
sp.add(light1);
scene.add(sp);

let cubeArrr = [];
for (let i = -5; i < 5; i++) {
  for (let j = -5; j < 5; j++) {
    for (let z = -5; z < 5; z++) {
      const cube = new THREE.InstancedMesh(cubeGeo, material, 10);
      cube.position.set(i, j, z);
      scene.add(cube);
      cubeArrr.push(cube);
    }
  }
}
/**
 * @description: @zww 监听鼠标移动
 * @param {*} event
 * @return {*}
 */
function onMouseMove(event) {
  let color = new THREE.Color();
  color.r = Math.random();
  color.g = Math.random();
  color.b = Math.random();
  const redMaterial = new THREE.MeshBasicMaterial({
    color: color
  });
  // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
  pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
  pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
  raycaster.setFromCamera(pointer, camera);
  // 计算物体和射线的焦点
  const intersects = raycaster.intersectObjects(cubeArrr);
  // console.log(intersects);
  for (let i = 0; i < intersects.length; i++) {
    intersects[0].object.material = redMaterial;
  }
}

/**
 * @description: @zww 创建多点打造粒子效果
 * @param {*}
 * @return {*}
 */
function generateGalaxy() {
  geom = new THREE.BufferGeometry();
  const positions = new Float32Array(params.count * 3);
  const colors = new Float32Array(params.count * 3);

  for (let i = 0; i < params.count; i++) {
    const current = i * 3;
    // 当前点再哪一条分支角度上
    const branchAngle = (i % params.branch) * ((2 * Math.PI) / params.branch);
    // 当前点距离圆心的距离
    let distance = Math.random() * params.radius * Math.pow(Math.random(), 3);
    const randomX = (Math.pow(Math.random() * 2 - 1, 3) * (params.radius - distance)) / 5;
    const randomY = (Math.pow(Math.random() * 2 - 1, 3) * (params.radius - distance)) / 5;
    const randomZ = (Math.pow(Math.random() * 2 - 1, 3) * (params.radius - distance)) / 5;
    positions[current] = Math.cos(branchAngle + distance * params.rotateRate) * distance + randomX;
    positions[current + 1] = 0 + randomY;
    positions[current + 2] = Math.sin(branchAngle + distance * params.rotateRate) * distance + randomZ;
    // 混合颜色生成渐变色
    const mixColor = startColor.clone();
    mixColor.lerp(endColor, distance / params.radius);
    colors[current] = mixColor.r;
    colors[current + 1] = mixColor.g;
    colors[current + 2] = mixColor.b;
  }
  geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
  geom.setAttribute('color', new THREE.BufferAttribute(colors, 3));
  material = new THREE.PointsMaterial({
    // color: new THREE.Color(params.color),
    size: params.size,
    sizeAttenuation: true,
    depthWrite: false,
    blending: THREE.AdditiveBlending,
    map: texture,
    alphaMap: texture,
    vertexColors: true,
    transparent: true
  });
  points = new THREE.Points(geom, material);
  scene.add(points);
}

/**
 * @description: @zww 在场景中添加实例
 * @param {*} scene
 * @param {*} camera
 * @return {*}
 */
function addToScene(scene, camera) {
  scene.add(camera);
}
/**
 * @description: @zww 更新渲染
 * @param {*}
 * @return {*}
 */
function render() {
  // 通过摄像机和鼠标位置更新射线
  // raycaster.setFromCamera(pointer, camera);

  // // 计算物体和射线的焦点
  // const intersects = raycaster.intersectObjects(scene.children);

  // for (let i = 0; i < intersects.length; i++) {
  //   intersects[i].object.material.color.set(0xff0000);
  // }
  controls.update();
  let time = clock.getElapsedTime();
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
/**
 * @description: @zww 监听页面变化
 * @param {*}
 * @return {*}
 */
window.addEventListener('resize', () => {
  console.log('画面变化');
  // 首先更新摄像头
  camera.aspect = window.innerWidth / window.innerHeight;
  // 然后更新摄像机的投影矩阵
  camera.updateProjectionMatrix();
  // 然后更新渲染器
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 屏幕像素比变化设置渲染器的像素比
  renderer.setPixelRatio(window.devicePixelRatio);
});

/**
 * @description: @zww 生成随机整数
 * @param {*} x 整数区间
 * @return {*}
 */
function intToNum(x) {
  let a = Math.random();
  let b = a * x;
  let c = Math.floor(b);
  return c;
}
/**
 * @description: @zww 创建gasp动画
 * @param {*}
 * @return {*}
 */
function animate(plane) {
  var tl = gsap.timeline({
    repeat: -1,
    repeatDelay: 0
  });
  tl.to(plane.rotation, {
    duration: 1,
    y: 0
  });
  tl.to(plane.rotation, {
    duration: 1,
    y: Math.PI / 6
  });
  tl.to(plane.rotation, {
    duration: 1,
    y: 0
  });
  tl.to(plane.rotation, {
    duration: 1,
    y: -Math.PI / 6
  });
  tl.to(plane.rotation, {
    duration: 1,
    y: 0
  });
}
/**
 * @description: @zww 创建gui见面
 * @param {*}
 * @return {*}
 */
function createGui() {
  const gui = new dat.GUI();
  let pos = ['x', 'y', 'z'];
  var folder = gui.addFolder('光源');
  var folder2 = gui.addFolder('球球');
  var palette = {
    color1: '#FF0000'
  };
  folder
    .addColor(palette, 'color1')
    .name(`光源颜色`)
    .onChange(value => {});
}
